<!DOCTYPE html>



  


<html class="theme-next pisces use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.8.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="NIO,JAVA7,非阻塞和阻塞,通道和选择器,">










<meta name="description" content="NIO入门基本教程">
<meta name="keywords" content="NIO,JAVA7,非阻塞和阻塞,通道和选择器">
<meta property="og:type" content="article">
<meta property="og:title" content="nio基本概念和快速入门">
<meta property="og:url" content="https://www.babywang.huangsm.xyz/2019/03/01/nio基本概念和快速入门、/index.html">
<meta property="og:site_name" content="babybabywang">
<meta property="og:description" content="NIO入门基本教程">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="https://www.babywang.huangsm.xyz/2019/03/01/nio基本概念和快速入门、/nio与io的区别.png">
<meta property="og:image" content="https://www.babywang.huangsm.xyz/2019/03/01/nio基本概念和快速入门、/缓冲区基本概念.png">
<meta property="og:image" content="https://www.babywang.huangsm.xyz/2019/03/01/nio基本概念和快速入门、/buffer的常用方法.png">
<meta property="og:image" content="https://www.babywang.huangsm.xyz/2019/03/01/nio基本概念和快速入门、/非直接缓冲区.png">
<meta property="og:image" content="https://www.babywang.huangsm.xyz/2019/03/01/nio基本概念和快速入门、/直接缓冲区.png">
<meta property="og:image" content="https://www.babywang.huangsm.xyz/2019/03/01/nio基本概念和快速入门、/通道(Channel">
<meta property="og:image" content="https://www.babywang.huangsm.xyz/2019/03/01/nio基本概念和快速入门、/DMA直接存储器.png">
<meta property="og:image" content="https://www.babywang.huangsm.xyz/2019/03/01/nio基本概念和快速入门、/通道控制IO.png">
<meta property="og:image" content="https://www.babywang.huangsm.xyz/2019/03/01/nio基本概念和快速入门、/分散和聚集.png">
<meta property="og:image" content="https://www.babywang.huangsm.xyz/2019/03/01/nio基本概念和快速入门、/聚集.png">
<meta property="og:image" content="https://www.babywang.huangsm.xyz/2019/03/01/nio基本概念和快速入门、/channel常用方法.png">
<meta property="og:image" content="https://www.babywang.huangsm.xyz/2019/03/01/nio基本概念和快速入门、/SelectableChannel的结构.png">
<meta property="og:image" content="https://www.babywang.huangsm.xyz/2019/03/01/nio基本概念和快速入门、/SelectionKey操作.png">
<meta property="og:image" content="https://www.babywang.huangsm.xyz/2019/03/01/nio基本概念和快速入门、/Selector常用方法.png">
<meta property="og:image" content="https://www.babywang.huangsm.xyz/2019/03/01/nio基本概念和快速入门、/Pipe管道.png">
<meta property="og:image" content="https://www.babywang.huangsm.xyz/2019/03/01/nio基本概念和快速入门、/paths的常用用法.png">
<meta property="og:image" content="https://www.babywang.huangsm.xyz/2019/03/01/nio基本概念和快速入门、/自动资源管理.png">
<meta property="og:updated_time" content="2019-03-02T13:53:54.455Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="nio基本概念和快速入门">
<meta name="twitter:description" content="NIO入门基本教程">
<meta name="twitter:image" content="https://www.babywang.huangsm.xyz/2019/03/01/nio基本概念和快速入门、/nio与io的区别.png">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Pisces',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: 'Author'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://www.babywang.huangsm.xyz/2019/03/01/nio基本概念和快速入门、/">





  <title>nio基本概念和快速入门 | babybabywang</title>
  








</head>
<!-- С���� <script type="text/javascript" src="/js/src/love.js"></script> -->

<body itemscope="" itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>
		<a href="https://github.com/babybabywang" class="github-corner" aria-label="View source on GitHub"><svg width="80" height="80" viewbox="0 0 250 250" style="fill:#151513; color:#fff; position: absolute; top: 0; border: 0; left: 0; transform: scale(-1, 1);" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"/><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"/><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"/></svg><style>.github-corner:hover .octo-arm{animation:octocat-wave 560ms ease-in-out}@keyframes octocat-wave{0%,100%{transform:rotate(0)}20%,60%{transform:rotate(-25deg)}40%,80%{transform:rotate(10deg)}}@media (max-width:500px){.github-corner:hover .octo-arm{animation:none}.github-corner .octo-arm{animation:octocat-wave 560ms ease-in-out}}</style></a>

    <header id="header" class="header" itemscope="" itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">babybabywang</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br>
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br>
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            归档
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope="" itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://www.babywang.huangsm.xyz/2019/03/01/nio基本概念和快速入门、/">

    <span hidden itemprop="author" itemscope="" itemtype="http://schema.org/Person">
      <meta itemprop="name" content="huangsm">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/blogHead.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope="" itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="babybabywang">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">nio基本概念和快速入门</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2019-03-01T20:37:19+08:00">
                2019-03-01
              </time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope="" itemtype="http://schema.org/Thing">
                  <a href="/categories/NIO/" itemprop="url" rel="index">
                    <span itemprop="name">NIO</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          
            <span class="post-meta-divider">|</span>
            <span class="page-pv"><i class="fa fa-file-o"></i>
            <span class="busuanzi-value" id="busuanzi_value_page_pv"></span>
            </span>
          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  5.9k
                </span>
              

              

              
            </div>
          

          
              <div class="post-description">
                  NIO入门基本教程
              </div>
          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h1 id="NIO快速入门"><a href="#NIO快速入门" class="headerlink" title="NIO快速入门"></a>NIO快速入门</h1><p><a href="https://gitee.com/wangyuanbaby/nio.git" target="_blank" rel="noopener">代码地址</a></p>
<h2 id="Java-NIO-简介"><a href="#Java-NIO-简介" class="headerlink" title="Java NIO 简介"></a>Java NIO 简介</h2><blockquote>
<p>Java NIO（New IO）是从Java 1.4版本开始引入的一个新的IO API，可以替代标准的Java IO API。<br>NIO与原来的IO有同样的作用和目的，但是使用的方式完全不同，NIO支持面向缓冲区的、基于<br>通道的IO操作。NIO将以更加高效的方式进行文件的读写操作。</p>
</blockquote>
<h2 id="Java-NIO-与-IO-的主要区别"><a href="#Java-NIO-与-IO-的主要区别" class="headerlink" title="Java NIO 与 IO 的主要区别"></a>Java NIO 与 IO 的主要区别</h2><p><img src="/2019/03/01/nio基本概念和快速入门、/nio与io的区别.png" alt="nio与io的区别"></p>
<h2 id="缓冲区-Buffer-和通道-Channel"><a href="#缓冲区-Buffer-和通道-Channel" class="headerlink" title="缓冲区(Buffer)和通道(Channel)"></a>缓冲区(Buffer)和通道(Channel)</h2><ul>
<li>Java NIO系统的核心在于：通道(Channel)和缓冲区(Buffer)。通道表示打开到 IO 设备(例如：文件、<br>套接字(网络))的连接。若需要使用 NIO 系统，需要获取用于连接 IO 设备的通道以及用于容纳数据的缓冲<br>区。然后操作缓冲区，对数据进行处理。</li>
</ul>
<p><code>简而言之，Channel 负责传输， Buffer 负责存储</code></p>
<h3 id="缓冲区"><a href="#缓冲区" class="headerlink" title="缓冲区"></a>缓冲区</h3><ul>
<li><p>缓冲区（Buffer）：一个用于特定基本数据类型的容器。由 java.nio 包定义的，所有缓冲区都是 Buffer 抽象类的子类。</p>
</li>
<li><p>Java NIO 中的 Buffer 主要用于与 NIO 通道进行交互，数据是从通道读入缓冲区，从缓冲区写入通道中的。</p>
</li>
<li><p>Buffer 就像一个数组，可以保存多个相同类型的数据。根据数据类型不同(boolean 除外) ，有以下 Buffer 常用子类：</p>
<ul>
<li>ByteBuffer</li>
<li>CharBuffer</li>
<li>LongBuffer</li>
<li>ShortBuffer</li>
<li>IntBuffer</li>
<li>FloatBuffer</li>
<li>DoubleBuffer</li>
</ul>
<blockquote>
<p>上述 Buffer 类 他们都采用相似的方法进行管理数据，只是各自管理的数据类型不同而已。都是通过如下方法获取一个 Buffer 对象：<br>static XxxBuffer allocate(int capacity) : 创建一个容量为 capacity 的 XxxBuffer 对象</p>
</blockquote>
</li>
</ul>
<h3 id="缓冲区的基本属性"><a href="#缓冲区的基本属性" class="headerlink" title="缓冲区的基本属性"></a>缓冲区的基本属性</h3><ul>
<li><p>Buffer 中的重要概念：</p>
<ul>
<li><p>容量 (capacity) ：表示 Buffer 最大数据容量，缓冲区容量不能为负，并且创建后不能更改。</p>
</li>
<li><p>限制 (limit)：第一个不应该读取或写入的数据的索引，即位于 limit 后的数据不可读写。缓冲区的限制不能为负，并且不能大于其容量。</p>
</li>
<li><p>位置 (position)：下一个要读取或写入的数据的索引。缓冲区的位置不能为负，并且不能大于其限制</p>
</li>
<li><p>标记 (mark)与重置 (reset)：标记是一个索引，通过 Buffer 中的 mark() 方法指定 Buffer 中一个特定的 position，之后可以通过调用 reset() 方法恢复到这个 position</p>
</li>
</ul>
</li>
</ul>
<p><strong>标记、位置、限制、容量遵守以下不变式： 0 &lt;= mark &lt;= position &lt;= limit &lt;= capacity</strong></p>
<p><img src="/2019/03/01/nio基本概念和快速入门、/缓冲区基本概念.png" alt="缓冲区基本概念"></p>
<h3 id="Buffer-的常用方法"><a href="#Buffer-的常用方法" class="headerlink" title="Buffer 的常用方法"></a>Buffer 的常用方法</h3><p><img src="/2019/03/01/nio基本概念和快速入门、/buffer的常用方法.png" alt="buffer的常用方法"></p>
<h3 id="缓冲区的数据操作"><a href="#缓冲区的数据操作" class="headerlink" title="缓冲区的数据操作"></a>缓冲区的数据操作</h3><ul>
<li><p>Buffer 所有子类提供了两个用于数据操作的方法：get() 与 put() 方法</p>
</li>
<li><p>获取 Buffer 中的数据</p>
<ul>
<li>get() ：读取单个字节</li>
<li>get(byte[] dst)：批量读取多个字节到 dst中</li>
<li>get(int index)：读取指定索引位置的字节(不会移动 position)</li>
</ul>
</li>
<li><p>放入数据到 Buffer中</p>
<ul>
<li>put(byte b)：将给定单个字节写入缓冲区的当前位置</li>
<li>put(byte[] src)：将 src 中的字节写入缓冲区的当前位置</li>
<li>put(int index, byte b)：将指定字节写入缓冲区的索引位置(不会移动 position)</li>
</ul>
</li>
</ul>
<h3 id="直接缓冲区与非直接缓冲区"><a href="#直接缓冲区与非直接缓冲区" class="headerlink" title="直接缓冲区与非直接缓冲区"></a>直接缓冲区与非直接缓冲区</h3><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">* 非直接缓冲区:通过allocate()方法分配缓冲区，将缓冲区建立在JVM的内存中</span><br><span class="line">* 直接缓冲区:通过allocateDirect()方法分配直接缓冲区，将缓冲区建立在物理内存中。可以提高效率</span><br></pre></td></tr></table></figure>
<ul>
<li>字节缓冲区要么是直接的，要么是非直接的。如果为直接字节缓冲区，则 Java 虚拟机会尽最大努力直接在此缓冲区上执行本机 I/O 操作。也就是说，在每次调用基础操作系统的一个本机 I/O 操作之前（或之后），虚拟机都会尽量避免将缓冲区的内容复制到中间缓冲区中（或从中间缓冲区中复制内容）。</li>
<li>直接字节缓冲区可以通过调用此类的 allocateDirect() 工厂方法来创建。此方法返回的缓冲区进行分配和取分配所需成本通常高于非直接缓冲区。直接缓冲区的内容可以驻留在常规的垃圾回收堆之外，因此，它们对应程序的内存需求量造成的影响可能并不明显。所以，建议将直接缓冲区主要分配给那些易受基础系统的本机 I/O操作影响的大型、持久的缓冲区。一般情况下，最好仅在直接缓冲区能在程序性能方面带来明显好处时分配它们。</li>
<li>直接字节缓冲区还可以通过 FileChannel 的 map() 方法 将文件区域直接映射到内存中来创建。该方法返回MappedByteBuffer 。Java 平台的实现有助于通过 JNI 从本机代码创建直接字节缓冲区。如果以上这些缓冲区中的某个缓冲区实例指的是不可访问的内存区域，则试图访问该区域不会更改该缓冲区的内容，并且将会在访问期间或稍后的某个时间导致抛出不确定的异常。</li>
<li><p>字节缓冲区是直接缓冲区还是非直接缓冲区可通过调用其 isDirect() 方法来确定。提供此方法是为了能够在性能关键型代码中执行显式缓冲区管理。</p>
<p><img src="/2019/03/01/nio基本概念和快速入门、/非直接缓冲区.png" alt="非直接缓冲区"></p>
</li>
</ul>
<p><img src="/2019/03/01/nio基本概念和快速入门、/直接缓冲区.png" alt="直接缓冲区"></p>
<h3 id="本节代码案例"><a href="#本节代码案例" class="headerlink" title="本节代码案例"></a>本节代码案例</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.huangsm.nio.buffer;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> org.junit.Test;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> java.nio.ByteBuffer;</span><br><span class="line"><span class="keyword">import</span> java.util.Dictionary;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 一、缓冲区(Buffer):在Java NIO中负责数据的存取。缓冲区就是数组。用于存储不同数据类型的数据</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> * 根据数据类型不同(boolean除外)。提供了相应类型的缓冲区</span></span><br><span class="line"><span class="comment"> * ByteBuffer</span></span><br><span class="line"><span class="comment"> * LongBuffer</span></span><br><span class="line"><span class="comment"> * IntBuffer</span></span><br><span class="line"><span class="comment"> * DoubleBuffer</span></span><br><span class="line"><span class="comment"> * FloatBuffer</span></span><br><span class="line"><span class="comment"> * ShortBuffer</span></span><br><span class="line"><span class="comment"> * CharBuffer</span></span><br><span class="line"><span class="comment"> * 上述缓冲区的管理方式几乎一致，通过allocate()获取缓冲区</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> * 二、缓冲区存取数据的两个核心方法</span></span><br><span class="line"><span class="comment"> * put():存入数据到缓冲区</span></span><br><span class="line"><span class="comment"> * get():从缓冲区中取数据</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> * 三、缓冲区中的四个核心属性:</span></span><br><span class="line"><span class="comment"> * capacity:容量，表示缓冲区中最大存储数据的容量。一旦声明不能改变。</span></span><br><span class="line"><span class="comment"> * limit:界限，表示缓冲区中可以操作数据的大小。(limit后数据不能进行读写)</span></span><br><span class="line"><span class="comment"> * position:位置,标识缓冲区正在操作数据的位置。</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> *mark:标记，表示记录当前position的位置。可以通过reset()恢复到mark的位置</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> * 0&lt;=mark&lt;=position&lt;=limit&lt;=capacity</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> * 五、直接缓冲区与非直接缓冲区:</span></span><br><span class="line"><span class="comment"> * 非直接缓冲区:通过allocate()方法分配缓冲区，将缓冲区建立在JVM的内存中</span></span><br><span class="line"><span class="comment"> * 直接缓冲区:通过allocateDirect()方法分配直接缓冲区，将缓冲区建立在物理内存中。可以提高效率</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@author</span> huangsm</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@version</span> V1.0</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">TestBuffer</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Test</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">tset3</span><span class="params">()</span></span>&#123;</span><br><span class="line">        <span class="comment">//创建直接缓冲区</span></span><br><span class="line">        ByteBuffer byteBuffer = ByteBuffer.allocateDirect(<span class="number">2</span>);</span><br><span class="line">        System.out.println(byteBuffer.isDirect());</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Test</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">test2</span><span class="params">()</span></span>&#123;</span><br><span class="line">        String str=<span class="string">"abcde"</span>;</span><br><span class="line">        ByteBuffer buf = ByteBuffer.allocate(<span class="number">1024</span>);</span><br><span class="line">        buf.put(str.getBytes());</span><br><span class="line">        buf.flip();</span><br><span class="line">        <span class="keyword">byte</span>[] dst=<span class="keyword">new</span> <span class="keyword">byte</span>[buf.limit()];</span><br><span class="line">        buf.get(dst,<span class="number">0</span>,<span class="number">2</span>);</span><br><span class="line">        System.out.println(<span class="keyword">new</span> String(dst,<span class="number">0</span>,dst.length));</span><br><span class="line">        System.out.println(buf.position());<span class="comment">//2</span></span><br><span class="line">        <span class="comment">//mark()标记</span></span><br><span class="line">        buf.mark();</span><br><span class="line">        buf.get(dst,<span class="number">2</span>,<span class="number">2</span>);</span><br><span class="line">        System.out.println(<span class="keyword">new</span> String(dst,<span class="number">0</span>,<span class="number">2</span>));</span><br><span class="line">        System.out.println(buf.position());<span class="comment">//4</span></span><br><span class="line">      <span class="comment">//  reset():恢复到mark的位置</span></span><br><span class="line">         buf.reset();</span><br><span class="line">       System.out.println(buf.position());</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Test</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">test1</span><span class="params">()</span></span>&#123;</span><br><span class="line">        String str=<span class="string">"abcde"</span>;</span><br><span class="line"></span><br><span class="line">        <span class="comment">//1.分配一个指定大小的缓冲区</span></span><br><span class="line">        ByteBuffer buf = ByteBuffer.allocate(<span class="number">10</span>);</span><br><span class="line">        System.out.println(<span class="string">"------allocate-------"</span>);</span><br><span class="line">        System.out.print(buf.position()+<span class="string">" "</span>);<span class="comment">//0</span></span><br><span class="line">        System.out.print(buf.capacity()+<span class="string">" "</span>);<span class="comment">//10</span></span><br><span class="line">        System.out.println(buf.limit());<span class="comment">//10</span></span><br><span class="line"></span><br><span class="line">        <span class="comment">//2.利用put()存入数据到缓冲区中 写模式</span></span><br><span class="line">        buf.put(str.getBytes());</span><br><span class="line">        System.out.println(<span class="string">"------put-------"</span>);</span><br><span class="line">        System.out.print(buf.position()+<span class="string">" "</span>);<span class="comment">//5</span></span><br><span class="line">        System.out.print(buf.capacity()+<span class="string">" "</span>);<span class="comment">//10</span></span><br><span class="line">        System.out.println(buf.limit());<span class="comment">//10</span></span><br><span class="line">        <span class="comment">//3.将写模式转换为读模式</span></span><br><span class="line">        buf.flip();</span><br><span class="line">        System.out.println(<span class="string">"------flip-------"</span>);</span><br><span class="line">        System.out.print(buf.position()+<span class="string">" "</span>);<span class="comment">//0</span></span><br><span class="line">        System.out.print(buf.capacity()+<span class="string">" "</span>);<span class="comment">//10</span></span><br><span class="line">        System.out.println(buf.limit());<span class="comment">//5</span></span><br><span class="line">        <span class="comment">//4.利用get()读取缓冲区中的数据</span></span><br><span class="line">        <span class="keyword">byte</span>[] dst=<span class="keyword">new</span> <span class="keyword">byte</span>[buf.limit()];</span><br><span class="line">        buf.get(dst);</span><br><span class="line">        System.out.println(<span class="keyword">new</span> String(dst,<span class="number">0</span>,dst.length));</span><br><span class="line">        System.out.println(<span class="string">"------get-------"</span>);</span><br><span class="line">        System.out.print(buf.position()+<span class="string">" "</span>);<span class="comment">//5</span></span><br><span class="line">        System.out.print(buf.capacity()+<span class="string">" "</span>);<span class="comment">//10</span></span><br><span class="line">        System.out.println(buf.limit()+<span class="string">" "</span>);<span class="comment">//5</span></span><br><span class="line">        <span class="comment">//5.rewind():可重复度</span></span><br><span class="line">        buf.rewind();</span><br><span class="line">        System.out.println(<span class="string">"------rewind-------"</span>);</span><br><span class="line">        System.out.print(buf.position()+<span class="string">" "</span>);<span class="comment">//0</span></span><br><span class="line">        System.out.print(buf.capacity()+<span class="string">" "</span>);<span class="comment">//10</span></span><br><span class="line">        System.out.println(buf.limit()+<span class="string">" "</span>);<span class="comment">//5</span></span><br><span class="line">        <span class="comment">//6.clear():清空缓冲区,缓冲区数据依然存在，只不过缓存区数据处于被遗忘状态</span></span><br><span class="line">        buf.clear();</span><br><span class="line">        System.out.println(<span class="string">"-----clear-----"</span>);</span><br><span class="line">        System.out.print(buf.position()+<span class="string">" "</span>);<span class="comment">//0</span></span><br><span class="line">        System.out.print(buf.capacity()+<span class="string">" "</span>);<span class="comment">//10</span></span><br><span class="line">        System.out.println(buf.limit()+<span class="string">" "</span>);<span class="comment">//10</span></span><br><span class="line">        <span class="keyword">byte</span> b = buf.get(<span class="number">1</span>);</span><br><span class="line">        System.out.println((<span class="keyword">char</span>)b);</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="文件通道-FileChannel"><a href="#文件通道-FileChannel" class="headerlink" title="文件通道(FileChannel)"></a>文件通道(FileChannel)</h2><ul>
<li>通道（Channel）：由 java.nio.channels 包定义的。Channel 表示 IO 源与目标打开的连接。Channel 类似于传统的“流”。只不过 Channel 本身不能直接访问数据，Channel 只能与Buffer 进行交互。</li>
</ul>
<h4 id="原始情况有CPU控制IO"><a href="#原始情况有CPU控制IO" class="headerlink" title="原始情况有CPU控制IO"></a>原始情况有CPU控制IO</h4><p><img src="/2019/03/01/nio基本概念和快速入门、/通道(Channel" alt="通道(Channel)">.png)</p>
<h4 id="DMA直接存储器"><a href="#DMA直接存储器" class="headerlink" title="DMA直接存储器"></a>DMA直接存储器</h4><p><img src="/2019/03/01/nio基本概念和快速入门、/DMA直接存储器.png" alt="DMA直接存储器"></p>
<p><strong>通过DMA来操控IO接口，弊端:当IO流过多的情况下就会大量创建DMA总线，这样会造成总线冲突，因此会影响性能</strong></p>
<h4 id="通道-Channel方式"><a href="#通道-Channel方式" class="headerlink" title="通道(Channel方式)"></a>通道(Channel方式)</h4><p><img src="/2019/03/01/nio基本概念和快速入门、/通道控制IO.png" alt="通道控制IO"></p>
<ul>
<li><p>Java 为 Channel 接口提供的最主要实现类如下：</p>
<ul>
<li>FileChannel：用于读取、写入、映射和操作文件的通道。</li>
<li>DatagramChannel：通过 UDP 读写网络中的数据通道。</li>
<li>SocketChannel：通过 TCP 读写网络中的数据。</li>
<li>ServerSocketChannel：可以监听新进来的 TCP 连接，对每一个新进来的连接都会创建一个SocketChannel。</li>
</ul>
</li>
<li><p>获取通道的一种方式是对支持通道的对象调用getChannel() 方法。支持通道的类如下：</p>
<ul>
<li><p>本地IO</p>
<ul>
<li><p>FileInputStream/FileOutputStream</p>
</li>
<li><p>RandomAccessFile</p>
</li>
</ul>
</li>
<li><p>网络IO</p>
<ul>
<li><p>DatagramSocket</p>
</li>
<li><p>Socket</p>
</li>
<li><p>ServerSocket</p>
</li>
</ul>
</li>
</ul>
</li>
<li>在JDK 1.7中的NIO.2针对各个通道提供了一个静态方法open()</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">FileChannel.open(Paths.get(<span class="string">"2.jpg"</span>), StandardOpenOption.READ);</span><br></pre></td></tr></table></figure>
<ul>
<li>在JDK 1.7中的NI0.2的Files工具类的newByteChannel()</li>
</ul>
<h4 id="通道的数据传输"><a href="#通道的数据传输" class="headerlink" title="通道的数据传输"></a>通道的数据传输</h4><h4 id="分散-Scatter-和聚集-Gathe"><a href="#分散-Scatter-和聚集-Gathe" class="headerlink" title="分散(Scatter)和聚集(Gathe"></a>分散(Scatter)和聚集(Gathe</h4><ul>
<li>分散读取（Scattering Reads）是指从 Channel 中读取的数据“分散”到多个 Buffer 中。</li>
</ul>
<p><img src="/2019/03/01/nio基本概念和快速入门、/分散和聚集.png" alt="分散"></p>
<p><em>注意：按照缓冲区的顺序，从 Channel 中读取的数据依次将 Buffer 填满</em></p>
<ul>
<li>聚集写入（Gathering Writes）是指将多个 Buffer 中的数据“聚集”到 Channel。</li>
</ul>
<p><img src="/2019/03/01/nio基本概念和快速入门、/聚集.png" alt="聚集"></p>
<p><em>注意：按照缓冲区的顺序，写入 position 和 limit 之间的数据到 Channel</em></p>
<h4 id="通道之间的数据传输"><a href="#通道之间的数据传输" class="headerlink" title="通道之间的数据传输"></a>通道之间的数据传输</h4><ul>
<li>transferFrom():将数据从源通道传输到其他 Channel 中 </li>
<li>transferTo(): 将数据从源通道传输到其他 Channel</li>
</ul>
<h4 id="字符集-Charset"><a href="#字符集-Charset" class="headerlink" title="字符集(Charset)"></a>字符集(Charset)</h4><ul>
<li>编码: 字符串-&gt;字符数组</li>
<li>解码: 字符数组-&gt;字符串</li>
</ul>
<p><code>案例:打印字符集</code></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 字符集</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="meta">@Test</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">test5</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    <span class="comment">//查看支持多少中字符集</span></span><br><span class="line">    SortedMap&lt;String, Charset&gt; map = Charset.availableCharsets();</span><br><span class="line">    map.keySet().forEach(</span><br><span class="line">            System.out::println</span><br><span class="line">    );</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p><code>案例:编码与解码</code></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 编码与解码</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="meta">@Test</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">test6</span><span class="params">()</span> <span class="keyword">throws</span> CharacterCodingException </span>&#123;</span><br><span class="line">    Charset cs1 = Charset.forName(<span class="string">"GBK"</span>);</span><br><span class="line">    <span class="comment">//获取编码器</span></span><br><span class="line">    CharsetEncoder ce = cs1.newEncoder();</span><br><span class="line">    <span class="comment">//获取解码器</span></span><br><span class="line">    CharsetDecoder cd = cs1.newDecoder();</span><br><span class="line"></span><br><span class="line">    CharBuffer cBuf = CharBuffer.allocate(<span class="number">1024</span>);</span><br><span class="line">    cBuf.put(<span class="string">"huangsm 帅气"</span>);</span><br><span class="line">    cBuf.flip();</span><br><span class="line"></span><br><span class="line">    <span class="comment">//编码</span></span><br><span class="line">    ByteBuffer bBuf = ce.encode(cBuf);</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; <span class="number">12</span>; i++) &#123;</span><br><span class="line">        System.out.println(bBuf.get(i));</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">//解码</span></span><br><span class="line">    bBuf.flip();</span><br><span class="line">    CharBuffer dBuf = cd.decode(bBuf);</span><br><span class="line">    System.out.println(dBuf.toString());</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h4 id="FileChannel-的常用方法"><a href="#FileChannel-的常用方法" class="headerlink" title="FileChannel 的常用方法"></a>FileChannel 的常用方法</h4><p><img src="/2019/03/01/nio基本概念和快速入门、/channel常用方法.png" alt="channel常用方法"></p>
<h4 id="本节代码案例-1"><a href="#本节代码案例-1" class="headerlink" title="本节代码案例"></a>本节代码案例</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br><span class="line">138</span><br><span class="line">139</span><br><span class="line">140</span><br><span class="line">141</span><br><span class="line">142</span><br><span class="line">143</span><br><span class="line">144</span><br><span class="line">145</span><br><span class="line">146</span><br><span class="line">147</span><br><span class="line">148</span><br><span class="line">149</span><br><span class="line">150</span><br><span class="line">151</span><br><span class="line">152</span><br><span class="line">153</span><br><span class="line">154</span><br><span class="line">155</span><br><span class="line">156</span><br><span class="line">157</span><br><span class="line">158</span><br><span class="line">159</span><br><span class="line">160</span><br><span class="line">161</span><br><span class="line">162</span><br><span class="line">163</span><br><span class="line">164</span><br><span class="line">165</span><br><span class="line">166</span><br><span class="line">167</span><br><span class="line">168</span><br><span class="line">169</span><br><span class="line">170</span><br><span class="line">171</span><br><span class="line">172</span><br><span class="line">173</span><br><span class="line">174</span><br><span class="line">175</span><br><span class="line">176</span><br><span class="line">177</span><br><span class="line">178</span><br><span class="line">179</span><br><span class="line">180</span><br><span class="line">181</span><br><span class="line">182</span><br><span class="line">183</span><br><span class="line">184</span><br><span class="line">185</span><br><span class="line">186</span><br><span class="line">187</span><br><span class="line">188</span><br><span class="line">189</span><br><span class="line">190</span><br><span class="line">191</span><br><span class="line">192</span><br><span class="line">193</span><br><span class="line">194</span><br><span class="line">195</span><br><span class="line">196</span><br><span class="line">197</span><br><span class="line">198</span><br><span class="line">199</span><br><span class="line">200</span><br><span class="line">201</span><br><span class="line">202</span><br><span class="line">203</span><br><span class="line">204</span><br><span class="line">205</span><br><span class="line">206</span><br><span class="line">207</span><br><span class="line">208</span><br><span class="line">209</span><br><span class="line">210</span><br><span class="line">211</span><br><span class="line">212</span><br><span class="line">213</span><br><span class="line">214</span><br><span class="line">215</span><br><span class="line">216</span><br><span class="line">217</span><br><span class="line">218</span><br><span class="line">219</span><br><span class="line">220</span><br><span class="line">221</span><br><span class="line">222</span><br><span class="line">223</span><br><span class="line">224</span><br><span class="line">225</span><br><span class="line">226</span><br><span class="line">227</span><br><span class="line">228</span><br><span class="line">229</span><br><span class="line">230</span><br><span class="line">231</span><br><span class="line">232</span><br><span class="line">233</span><br><span class="line">234</span><br><span class="line">235</span><br><span class="line">236</span><br><span class="line">237</span><br><span class="line">238</span><br><span class="line">239</span><br><span class="line">240</span><br><span class="line">241</span><br><span class="line">242</span><br><span class="line">243</span><br><span class="line">244</span><br><span class="line">245</span><br><span class="line">246</span><br><span class="line">247</span><br><span class="line">248</span><br><span class="line">249</span><br><span class="line">250</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.huangsm.nio.channel;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> org.junit.Test;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> java.io.*;</span><br><span class="line"><span class="keyword">import</span> java.nio.ByteBuffer;</span><br><span class="line"><span class="keyword">import</span> java.nio.CharBuffer;</span><br><span class="line"><span class="keyword">import</span> java.nio.MappedByteBuffer;</span><br><span class="line"><span class="keyword">import</span> java.nio.channels.FileChannel;</span><br><span class="line"><span class="keyword">import</span> java.nio.charset.CharacterCodingException;</span><br><span class="line"><span class="keyword">import</span> java.nio.charset.Charset;</span><br><span class="line"><span class="keyword">import</span> java.nio.charset.CharsetDecoder;</span><br><span class="line"><span class="keyword">import</span> java.nio.charset.CharsetEncoder;</span><br><span class="line"><span class="keyword">import</span> java.nio.file.Paths;</span><br><span class="line"><span class="keyword">import</span> java.nio.file.StandardOpenOption;</span><br><span class="line"><span class="keyword">import</span> java.time.Duration;</span><br><span class="line"><span class="keyword">import</span> java.time.Instant;</span><br><span class="line"><span class="keyword">import</span> java.util.SortedMap;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 一、通道(Channel):用于源节点与目标节点的连接。在Java NIO中负责缓冲区中数据的传输。Channel本身不存储数据，因此需要配合缓冲区进行传输。</span></span><br><span class="line"><span class="comment"> * &lt;p&gt;</span></span><br><span class="line"><span class="comment"> * 二、通道的主要实现类</span></span><br><span class="line"><span class="comment"> * java.nio.channels.Channel接口:</span></span><br><span class="line"><span class="comment"> * |--FileChannel</span></span><br><span class="line"><span class="comment"> * |--SocketChannel TCP网络IO(套接字)</span></span><br><span class="line"><span class="comment"> * |--ServerSocketChannel</span></span><br><span class="line"><span class="comment"> * |--DatagramChannel UDP</span></span><br><span class="line"><span class="comment"> * &lt;p&gt;</span></span><br><span class="line"><span class="comment"> * 三、获取通道</span></span><br><span class="line"><span class="comment"> * 1. Java 针对支持通道的类提供了getChannel()方法</span></span><br><span class="line"><span class="comment"> * 本地IO:</span></span><br><span class="line"><span class="comment"> * FileInputStream/FileOutputStream</span></span><br><span class="line"><span class="comment"> * RandomAccessFile</span></span><br><span class="line"><span class="comment"> * 网络IO:</span></span><br><span class="line"><span class="comment"> * Socket</span></span><br><span class="line"><span class="comment"> * ServerSocket</span></span><br><span class="line"><span class="comment"> * DatagramSocket</span></span><br><span class="line"><span class="comment"> * 2. 在JDK 1.7中的NIO.2针对各个通道提供了一个静态方法open()</span></span><br><span class="line"><span class="comment"> * 3. 在JDK 1.7中的NI0.2的Files工具类的newByteChannel()</span></span><br><span class="line"><span class="comment"> * 四、通道之间的数据传输</span></span><br><span class="line"><span class="comment"> * transferFrom()</span></span><br><span class="line"><span class="comment"> * transferTo()</span></span><br><span class="line"><span class="comment"> * &lt;p&gt;</span></span><br><span class="line"><span class="comment"> * 五、分散(Scatter)与聚集(Gather)</span></span><br><span class="line"><span class="comment"> * 分散读取(Scattering Reads): 将通道中的数据分散到多个缓冲区中</span></span><br><span class="line"><span class="comment"> * 聚集写入(Gathering Writes): 将多个缓冲区中的数据聚集到一个通道中</span></span><br><span class="line"><span class="comment"> * &lt;p&gt;</span></span><br><span class="line"><span class="comment"> * 六、字符集:Charset</span></span><br><span class="line"><span class="comment"> * 编码:字符串-&gt;字节数组</span></span><br><span class="line"><span class="comment"> * 解码:字节数组-&gt;字符串</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">TestChannel</span> </span>&#123;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 编码与解码</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@Test</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">test6</span><span class="params">()</span> <span class="keyword">throws</span> CharacterCodingException </span>&#123;</span><br><span class="line">        Charset cs1 = Charset.forName(<span class="string">"GBK"</span>);</span><br><span class="line">        <span class="comment">//获取编码器</span></span><br><span class="line">        CharsetEncoder ce = cs1.newEncoder();</span><br><span class="line">        <span class="comment">//获取解码器</span></span><br><span class="line">        CharsetDecoder cd = cs1.newDecoder();</span><br><span class="line"></span><br><span class="line">        CharBuffer cBuf = CharBuffer.allocate(<span class="number">1024</span>);</span><br><span class="line">        cBuf.put(<span class="string">"huangsm 帅气"</span>);</span><br><span class="line">        cBuf.flip();</span><br><span class="line"></span><br><span class="line">        <span class="comment">//编码</span></span><br><span class="line">        ByteBuffer bBuf = ce.encode(cBuf);</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; <span class="number">12</span>; i++) &#123;</span><br><span class="line">            System.out.println(bBuf.get(i));</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">//解码</span></span><br><span class="line">        bBuf.flip();</span><br><span class="line">        CharBuffer dBuf = cd.decode(bBuf);</span><br><span class="line">        System.out.println(dBuf.toString());</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 字符集</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@Test</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">test5</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="comment">//查看支持多少中字符集</span></span><br><span class="line">        SortedMap&lt;String, Charset&gt; map = Charset.availableCharsets();</span><br><span class="line">        map.keySet().forEach(</span><br><span class="line">                System.out::println</span><br><span class="line">        );</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 分散和聚集</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@Test</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">tset4</span><span class="params">()</span> <span class="keyword">throws</span> IOException </span>&#123;</span><br><span class="line">        RandomAccessFile raf1 = <span class="keyword">new</span> RandomAccessFile(<span class="string">"1.txt"</span>, <span class="string">"rw"</span>);</span><br><span class="line">        <span class="comment">//1.获取通道</span></span><br><span class="line">        FileChannel channel1 = raf1.getChannel();</span><br><span class="line">        <span class="comment">//2.分配指定大小的缓冲区</span></span><br><span class="line">        ByteBuffer buf1 = ByteBuffer.allocate(<span class="number">100</span>);</span><br><span class="line">        ByteBuffer buf2 = ByteBuffer.allocate(<span class="number">1024</span>);</span><br><span class="line">        <span class="comment">//3.分散读取</span></span><br><span class="line">        ByteBuffer[] bufs = &#123;buf1, buf2&#125;;</span><br><span class="line">        channel1.read(bufs);</span><br><span class="line">        <span class="keyword">for</span> (ByteBuffer buf : bufs) &#123;</span><br><span class="line">            buf.flip();</span><br><span class="line">        &#125;</span><br><span class="line">        System.out.println(<span class="keyword">new</span> String(bufs[<span class="number">0</span>].array(), <span class="number">0</span>, bufs[<span class="number">0</span>].limit()));</span><br><span class="line">        System.out.println(<span class="string">"-------------------------------------------------"</span>);</span><br><span class="line">        System.out.println(<span class="keyword">new</span> String(bufs[<span class="number">1</span>].array(), <span class="number">0</span>, bufs[<span class="number">1</span>].limit()));</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">        <span class="comment">//4.聚集写入</span></span><br><span class="line">        RandomAccessFile raf2 = <span class="keyword">new</span> RandomAccessFile(<span class="string">"2.txt"</span>, <span class="string">"rw"</span>);</span><br><span class="line">        FileChannel channel = raf2.getChannel();</span><br><span class="line">        channel.write(bufs);</span><br><span class="line">        channel.close();</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 通道传输数据(这里异常就直接抛出去了)</span></span><br><span class="line"><span class="comment">     * 直接缓冲区的方式</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@Test</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">test3</span><span class="params">()</span> <span class="keyword">throws</span> IOException </span>&#123;</span><br><span class="line">        FileChannel inChannel = FileChannel.open(Paths.get(<span class="string">"2.jpg"</span>), StandardOpenOption.READ);</span><br><span class="line">        FileChannel outChannel = FileChannel.open(Paths.get(<span class="string">"5.jpg"</span>), StandardOpenOption.WRITE, StandardOpenOption.READ, StandardOpenOption.CREATE_NEW);</span><br><span class="line">        <span class="comment">//inChannel.transferTo(0, inChannel.size(), outChannel);</span></span><br><span class="line">        outChannel.transferFrom(inChannel, <span class="number">0</span>, inChannel.size());</span><br><span class="line">        inChannel.close();</span><br><span class="line">        outChannel.close();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 使用直接缓冲区完成文件的复制(内存映射文件只有ByteBuffer支持)</span></span><br><span class="line"><span class="comment">     * 使用JDK1.7提供的open()方法</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@Test</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">test2</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        Instant start = Instant.now();</span><br><span class="line">        <span class="comment">//使用JDK1.7的open()方法，读模式</span></span><br><span class="line">        FileChannel inChannel = <span class="keyword">null</span>;</span><br><span class="line">        FileChannel outChannel = <span class="keyword">null</span>;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            <span class="comment">//耗时150毫秒</span></span><br><span class="line">            inChannel = FileChannel.open(Paths.get(<span class="string">"1.avi"</span>), StandardOpenOption.READ);</span><br><span class="line">            <span class="comment">//CREATE_NEW不存在就创建，如果创建就报错，CREATE如果文件不存在就创建如果存在也创建。</span></span><br><span class="line">            outChannel = FileChannel.open(Paths.get(<span class="string">"2.avi"</span>), StandardOpenOption.WRITE, StandardOpenOption.READ, StandardOpenOption.CREATE_NEW);</span><br><span class="line"></span><br><span class="line">            <span class="comment">//内存映射文件</span></span><br><span class="line">            MappedByteBuffer inMappedBuf = inChannel.map(FileChannel.MapMode.READ_ONLY, <span class="number">0</span>, inChannel.size());</span><br><span class="line">            MappedByteBuffer outMappedBuf = outChannel.map(FileChannel.MapMode.READ_WRITE, <span class="number">0</span>, inChannel.size());</span><br><span class="line"></span><br><span class="line">            <span class="comment">//直接对缓冲区进行数据的读写操作</span></span><br><span class="line">            <span class="keyword">byte</span>[] dst = <span class="keyword">new</span> <span class="keyword">byte</span>[inMappedBuf.limit()];</span><br><span class="line">            inMappedBuf.get(dst);</span><br><span class="line">            outMappedBuf.put(dst);</span><br><span class="line">        &#125; <span class="keyword">catch</span> (IOException e) &#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">        &#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">            <span class="keyword">if</span> (inChannel != <span class="keyword">null</span>) &#123;</span><br><span class="line">                <span class="keyword">try</span> &#123;</span><br><span class="line">                    inChannel.close();</span><br><span class="line">                &#125; <span class="keyword">catch</span> (IOException e) &#123;</span><br><span class="line">                    e.printStackTrace();</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">if</span> (outChannel != <span class="keyword">null</span>) &#123;</span><br><span class="line">                <span class="keyword">try</span> &#123;</span><br><span class="line">                    outChannel.close();</span><br><span class="line">                &#125; <span class="keyword">catch</span> (IOException e) &#123;</span><br><span class="line">                    e.printStackTrace();</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        Instant end = Instant.now();</span><br><span class="line">        System.out.println(Duration.between(start, end).toMillis());</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 利用通道完成文件的负责 （非直接缓冲区）</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@Test</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">test1</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        Instant start = Instant.now();</span><br><span class="line">        FileInputStream fis = <span class="keyword">null</span>;</span><br><span class="line">        FileOutputStream fos = <span class="keyword">null</span>;</span><br><span class="line">        FileChannel inChannel = <span class="keyword">null</span>;</span><br><span class="line">        FileChannel outChannel = <span class="keyword">null</span>;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            <span class="comment">//耗时1366毫秒</span></span><br><span class="line">            fis = <span class="keyword">new</span> FileInputStream(<span class="string">"1.avi"</span>);</span><br><span class="line">            fos = <span class="keyword">new</span> FileOutputStream(<span class="string">"3.avi"</span>);</span><br><span class="line">            <span class="comment">//①获取通道</span></span><br><span class="line">            inChannel = fis.getChannel();</span><br><span class="line">            outChannel = fos.getChannel();</span><br><span class="line"></span><br><span class="line">            <span class="comment">//②分配指定大小缓冲区（非直接缓冲区）</span></span><br><span class="line">            ByteBuffer buf = ByteBuffer.allocate(<span class="number">1024</span>);</span><br><span class="line"></span><br><span class="line">            <span class="comment">//③将通道中的数据存入缓冲区中</span></span><br><span class="line">            <span class="keyword">while</span> (inChannel.read(buf) != -<span class="number">1</span>) &#123;</span><br><span class="line">                <span class="comment">//切换成读取数据模式</span></span><br><span class="line">                buf.flip();</span><br><span class="line">                <span class="comment">//④将缓冲区中的数据写入通道\</span></span><br><span class="line">                outChannel.write(buf);</span><br><span class="line">                <span class="comment">//清空缓冲区</span></span><br><span class="line">                buf.clear();</span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">        &#125; <span class="keyword">catch</span> (IOException e) &#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line"></span><br><span class="line">        &#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">            <span class="keyword">if</span> (outChannel != <span class="keyword">null</span>) &#123;</span><br><span class="line">                <span class="keyword">try</span> &#123;</span><br><span class="line">                    outChannel.close();</span><br><span class="line">                &#125; <span class="keyword">catch</span> (IOException e) &#123;</span><br><span class="line">                    e.printStackTrace();</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">if</span> (inChannel != <span class="keyword">null</span>) &#123;</span><br><span class="line">                <span class="keyword">try</span> &#123;</span><br><span class="line">                    inChannel.close();</span><br><span class="line">                &#125; <span class="keyword">catch</span> (IOException e) &#123;</span><br><span class="line">                    e.printStackTrace();</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">if</span> (fis != <span class="keyword">null</span>) &#123;</span><br><span class="line">                <span class="keyword">try</span> &#123;</span><br><span class="line">                    fis.close();</span><br><span class="line">                &#125; <span class="keyword">catch</span> (IOException e) &#123;</span><br><span class="line">                    e.printStackTrace();</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">if</span> (fos != <span class="keyword">null</span>) &#123;</span><br><span class="line">                <span class="keyword">try</span> &#123;</span><br><span class="line">                    fos.close();</span><br><span class="line">                &#125; <span class="keyword">catch</span> (IOException e) &#123;</span><br><span class="line">                    e.printStackTrace();</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        Instant end = Instant.now();</span><br><span class="line">        System.out.println(Duration.between(start, end).toMillis());</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="NIO-的非阻塞式网络通信"><a href="#NIO-的非阻塞式网络通信" class="headerlink" title="NIO 的非阻塞式网络通信"></a>NIO 的非阻塞式网络通信</h2><h3 id="阻塞与非阻塞"><a href="#阻塞与非阻塞" class="headerlink" title="阻塞与非阻塞"></a>阻塞与非阻塞</h3><ul>
<li>传统的 IO 流都是阻塞式的。也就是说，当一个线程调用 read() 或 write() 时，该线程被阻塞，直到有一些数据被读取或写入，该线程在此期间不能执行其他任务。因此，在完成网络通信进行 IO 操作时，由于线程会阻塞，所以服务器端必须为每个客户端都提供一个独立的线程进行处理，当服务器端需要处理大量客户端时，性能急剧下降。</li>
<li>Java NIO 是非阻塞模式的。当线程从某通道进行读写数据时，若没有数据可用时，该线程可以进行其他任务。线程通常将非阻塞 IO 的空闲时间用于在其他通道上执行 IO 操作，所以单独的线程可以管理多个输入和输出通道。因此，NIO 可以让服务器端使用一个或有限几个线程来同时处理连接到服务器端的所有客户端。</li>
</ul>
<h3 id="选择器-Selector"><a href="#选择器-Selector" class="headerlink" title="选择器(Selector)"></a>选择器(Selector)</h3><ul>
<li>选择器（Selector） 是 SelectableChannle 对象的多路复用器，Selector 可以同时监控多个 SelectableChannel 的 IO 状况，也就是说，利用 Selector 可使一个单独的线程管理多个 Channel。Selector 是非阻塞 IO 的核心。</li>
<li>SelectableChannle 的结构如下图：</li>
</ul>
<p><img src="/2019/03/01/nio基本概念和快速入门、/SelectableChannel的结构.png" alt="SelectableChannel的结构"></p>
<h4 id="选择器（Selector）的应用"><a href="#选择器（Selector）的应用" class="headerlink" title="选择器（Selector）的应用"></a>选择器（Selector）的应用</h4><ul>
<li>当调用 register(Selector sel, int ops) 将通道注册选择器时，选择器对通道的监听事件，需要通过第二个参数 ops 指定。</li>
<li>可以监听的事件类型（可使用 SelectionKey 的四个常量表示）：<ul>
<li>读 : SelectionKey.OP_READ （1）</li>
<li>写 : SelectionKey.OP_WRITE （4）</li>
<li>连接 : SelectionKey.OP_CONNECT （8）</li>
<li>接收 : SelectionKey.OP_ACCEPT （16）</li>
</ul>
</li>
<li>若注册时不止监听一个事件，则可以使用“位或”操作符连接。</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">SelectionKey.OP_ACCEPT|SelectionKey.OP_READ</span><br></pre></td></tr></table></figure>
<h4 id="SelectionKey"><a href="#SelectionKey" class="headerlink" title="SelectionKey"></a>SelectionKey</h4><ul>
<li>SelectionKey：表示 SelectableChannel 和 Selector 之间的注册关系。每次向选择器注册通道时就会选择一个事件(选择键)。选择键包含两个表示为整数值的操作集。操作集的每一位都表示该键的通道所支持的一类可选择操作。</li>
</ul>
<p><img src="/2019/03/01/nio基本概念和快速入门、/SelectionKey操作.png" alt="SelectionKey操作"></p>
<h4 id="Selector-的常用方法"><a href="#Selector-的常用方法" class="headerlink" title="Selector 的常用方法"></a>Selector 的常用方法</h4><p><img src="/2019/03/01/nio基本概念和快速入门、/Selector常用方法.png" alt="Selector常用方法"></p>
<h3 id="SocketChannel"><a href="#SocketChannel" class="headerlink" title="SocketChannel"></a>SocketChannel</h3><ul>
<li><p>Java NIO中的SocketChannel是一个连接到TCP网络套接字的通道。</p>
</li>
<li><p>操作步骤：</p>
<ul>
<li>打开 SocketChannel</li>
<li>读写数据</li>
<li>关闭 SocketChannel</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//1.获取通道</span></span><br><span class="line">SocketChannel sChannel = SocketChannel.open(<span class="keyword">new</span> InetSocketAddress(<span class="string">"127.0.0.1"</span>, <span class="number">8080</span>));</span><br><span class="line"><span class="comment">//2.切换非阻塞模式</span></span><br><span class="line">sChannel.configureBlocking(<span class="keyword">false</span>);</span><br><span class="line"></span><br><span class="line"><span class="comment">//3.分配一个指定大小的缓冲区</span></span><br><span class="line">ByteBuffer buf = ByteBuffer.allocate(<span class="number">1024</span>);</span><br><span class="line"></span><br><span class="line"><span class="comment">//4.发送数据给服务端</span></span><br><span class="line">Scanner scan=<span class="keyword">new</span> Scanner(System.in);</span><br><span class="line"><span class="keyword">while</span> (scan.hasNext())&#123;</span><br><span class="line">    String str=scan.next();</span><br><span class="line">    buf.put((LocalDateTime.now().toString()+<span class="string">"\n"</span>+str).getBytes());</span><br><span class="line">    buf.flip();</span><br><span class="line">    sChannel.write(buf);</span><br><span class="line">    buf.clear();</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">sChannel.close();</span><br></pre></td></tr></table></figure>
</li>
</ul>
<h3 id="ServerSocketChannel"><a href="#ServerSocketChannel" class="headerlink" title="ServerSocketChannel"></a>ServerSocketChannel</h3><ul>
<li>Java NIO中的 ServerSocketChannel 是一个可以监听新进来的TCP连接的通道，就像标准IO中的ServerSocket一样。</li>
</ul>
<h3 id="DatagramChannel"><a href="#DatagramChannel" class="headerlink" title="DatagramChannel"></a>DatagramChannel</h3><ul>
<li>Java NIO中的DatagramChannel是一个能收发UDP包的通道。</li>
<li>操作步骤：<ul>
<li>打开 DatagramChannel</li>
<li>接收/发送数据</li>
</ul>
</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">DatagramChannel dc = DatagramChannel.open();</span><br><span class="line">dc.configureBlocking(<span class="keyword">false</span>);</span><br><span class="line">ByteBuffer buf = ByteBuffer.allocate(<span class="number">1024</span>);</span><br><span class="line">buf.put(LocalDate.now().toString().getBytes());</span><br><span class="line">buf.flip();</span><br><span class="line">dc.send(buf, <span class="keyword">new</span> InetSocketAddress(<span class="string">"127.0.0.1"</span>, <span class="number">8080</span>));</span><br><span class="line">buf.clear();</span><br><span class="line"></span><br><span class="line">dc.close();</span><br></pre></td></tr></table></figure>
<h3 id="最终代码"><a href="#最终代码" class="headerlink" title="最终代码"></a>最终代码</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.huangsm.nio.socket;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> org.junit.Test;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> java.io.IOException;</span><br><span class="line"><span class="keyword">import</span> java.net.InetSocketAddress;</span><br><span class="line"><span class="keyword">import</span> java.nio.ByteBuffer;</span><br><span class="line"><span class="keyword">import</span> java.nio.channels.*;</span><br><span class="line"><span class="keyword">import</span> java.time.LocalDateTime;</span><br><span class="line"><span class="keyword">import</span> java.util.Iterator;</span><br><span class="line"><span class="keyword">import</span> java.util.Scanner;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 一、使用NIO完成网络通信的三个核心:</span></span><br><span class="line"><span class="comment"> * 1.通道(Channel):负责连接</span></span><br><span class="line"><span class="comment"> * java.nio.channels.Channel接口:</span></span><br><span class="line"><span class="comment"> * |-- SelectableChannel 抽象类</span></span><br><span class="line"><span class="comment"> * |--SocketChannel</span></span><br><span class="line"><span class="comment"> * |--ServerSocketChannel</span></span><br><span class="line"><span class="comment"> * |--DatagramChannel</span></span><br><span class="line"><span class="comment"> * &lt;p&gt;</span></span><br><span class="line"><span class="comment"> * |--Pipe.SinkChannel</span></span><br><span class="line"><span class="comment"> * |--Pipe.SourceChannel</span></span><br><span class="line"><span class="comment"> * 2.缓冲区(Buffer):负责数据的存取</span></span><br><span class="line"><span class="comment"> * 3.选择器(Selector):是SelectableChannel的多路复用器。用于监控SelectableChannel的IO状况</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">TestNoBlockingNIO</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Test</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">client</span><span class="params">()</span> <span class="keyword">throws</span> IOException </span>&#123;</span><br><span class="line">        <span class="comment">//1.获取通道</span></span><br><span class="line">        SocketChannel sChannel = SocketChannel.open(<span class="keyword">new</span> InetSocketAddress(<span class="string">"127.0.0.1"</span>, <span class="number">8080</span>));</span><br><span class="line">        <span class="comment">//2.切换非阻塞模式</span></span><br><span class="line">        sChannel.configureBlocking(<span class="keyword">false</span>);</span><br><span class="line"></span><br><span class="line">        <span class="comment">//3.分配一个指定大小的缓冲区</span></span><br><span class="line">        ByteBuffer buf = ByteBuffer.allocate(<span class="number">1024</span>);</span><br><span class="line"></span><br><span class="line">        <span class="comment">//4.发送数据给服务端</span></span><br><span class="line">        Scanner scan=<span class="keyword">new</span> Scanner(System.in);</span><br><span class="line">        <span class="keyword">while</span> (scan.hasNext())&#123;</span><br><span class="line">            String str=scan.next();</span><br><span class="line">            buf.put((LocalDateTime.now().toString()+<span class="string">"\n"</span>+str).getBytes());</span><br><span class="line">            buf.flip();</span><br><span class="line">            sChannel.write(buf);</span><br><span class="line">            buf.clear();</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        sChannel.close();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Test</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">server</span><span class="params">()</span> <span class="keyword">throws</span> IOException </span>&#123;</span><br><span class="line">        <span class="comment">//1.获取通道</span></span><br><span class="line">        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();</span><br><span class="line"></span><br><span class="line">        <span class="comment">//2.切换成非阻塞模式</span></span><br><span class="line">        serverSocketChannel.configureBlocking(<span class="keyword">false</span>);</span><br><span class="line"></span><br><span class="line">        <span class="comment">//3.绑定连接、</span></span><br><span class="line">        serverSocketChannel.bind(<span class="keyword">new</span> InetSocketAddress(<span class="number">8080</span>));</span><br><span class="line"></span><br><span class="line">        <span class="comment">//4.获取选择器</span></span><br><span class="line">        Selector selector = Selector.open();</span><br><span class="line"></span><br><span class="line">        <span class="comment">//5.将通道注册到选择器上,并且指定“监听接收事件”</span></span><br><span class="line">        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);</span><br><span class="line"></span><br><span class="line">        <span class="comment">//6.轮询式的获取选择器上已经“准备就绪”的事件</span></span><br><span class="line">        <span class="keyword">while</span> (selector.select() &gt; <span class="number">0</span>) &#123;</span><br><span class="line">            <span class="comment">//7.获取当前选择器中所有注册的“选择键（已就绪的监听事件）”</span></span><br><span class="line">            Iterator&lt;SelectionKey&gt; it = selector.selectedKeys().iterator();</span><br><span class="line">            <span class="keyword">while</span> (it.hasNext()) &#123;</span><br><span class="line">                <span class="comment">//8.获取准备“就绪”的是事件</span></span><br><span class="line">                SelectionKey sk = it.next();</span><br><span class="line">                <span class="comment">//9. 判断具体是什么事件准备就绪</span></span><br><span class="line">                <span class="keyword">if</span> (sk.isAcceptable()) &#123;</span><br><span class="line">                    <span class="comment">//10. 若“接收就绪”，获取客户端连接</span></span><br><span class="line">                    SocketChannel sChannel = serverSocketChannel.accept();</span><br><span class="line"></span><br><span class="line">                    <span class="comment">//11. 切换非阻塞模式</span></span><br><span class="line">                    sChannel.configureBlocking(<span class="keyword">false</span>);</span><br><span class="line"></span><br><span class="line">                    <span class="comment">//12. 将该通道注册到选择器上</span></span><br><span class="line">                    sChannel.register(selector, SelectionKey.OP_READ);</span><br><span class="line">                &#125; <span class="keyword">else</span> <span class="keyword">if</span> (sk.isReadable()) &#123;</span><br><span class="line">                    <span class="comment">//13. 获取当前选择器上“读就绪”状态的通道</span></span><br><span class="line">                    SocketChannel sChannel = (SocketChannel) sk.channel();</span><br><span class="line"></span><br><span class="line">                    <span class="comment">//14. 读取数据</span></span><br><span class="line">                    ByteBuffer buf = ByteBuffer.allocate(<span class="number">1024</span>);</span><br><span class="line"></span><br><span class="line">                    <span class="keyword">int</span> len = <span class="number">0</span>;</span><br><span class="line">                    <span class="keyword">while</span> ((len = sChannel.read(buf)) &gt; <span class="number">0</span>) &#123;</span><br><span class="line">                        buf.flip();</span><br><span class="line">                        System.out.println(<span class="keyword">new</span> String(buf.array(), <span class="number">0</span>, len));</span><br><span class="line">                        buf.clear();</span><br><span class="line">                    &#125;</span><br><span class="line">                &#125;</span><br><span class="line">                <span class="comment">//15. 取消选择键 SelectionKey</span></span><br><span class="line">                it.remove();</span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="管道-Pipe"><a href="#管道-Pipe" class="headerlink" title="管道(Pipe)"></a>管道(Pipe)</h2><ul>
<li>ava NIO 管道是2个线程之间的单向数据连接。Pipe有一个source通道和一个sink通道。数据会被写到sink通道，从source通道读取。</li>
</ul>
<p><img src="/2019/03/01/nio基本概念和快速入门、/Pipe管道.png" alt="Pipe管道"></p>
<h3 id="代码"><a href="#代码" class="headerlink" title="代码"></a>代码</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.huangsm.nio.pipe;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> org.junit.Test;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> java.io.IOException;</span><br><span class="line"><span class="keyword">import</span> java.nio.ByteBuffer;</span><br><span class="line"><span class="keyword">import</span> java.nio.channels.Pipe;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">TestPipe</span> </span>&#123;</span><br><span class="line">    <span class="meta">@Test</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">test1</span><span class="params">()</span> <span class="keyword">throws</span> IOException </span>&#123;</span><br><span class="line">        <span class="comment">//1.获取管道</span></span><br><span class="line">        Pipe pipe=Pipe.open();</span><br><span class="line">        <span class="comment">//2.将缓冲区中的数据写入管道</span></span><br><span class="line">        ByteBuffer buf = ByteBuffer.allocate(<span class="number">1024</span>);</span><br><span class="line">        Pipe.SinkChannel sinkChannel = pipe.sink();</span><br><span class="line">        <span class="comment">//3.写入数据</span></span><br><span class="line">        buf.put(<span class="string">"通过单向管道发送数据"</span>.getBytes());</span><br><span class="line">        buf.flip();</span><br><span class="line">        sinkChannel.write(buf);</span><br><span class="line"></span><br><span class="line">        <span class="comment">//3.pipe读取缓冲区的数据</span></span><br><span class="line">        Pipe.SourceChannel sourceChannel = pipe.source();</span><br><span class="line">        buf.flip();</span><br><span class="line">        <span class="keyword">int</span> len = sourceChannel.read(buf);</span><br><span class="line">        System.out.println(<span class="keyword">new</span> String(buf.array(),<span class="number">0</span>,len));</span><br><span class="line">        sourceChannel.close();</span><br><span class="line">        sinkChannel.close();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="Java-NIO2-Path、Paths-与-Files"><a href="#Java-NIO2-Path、Paths-与-Files" class="headerlink" title="Java NIO2 (Path、Paths 与 Files)"></a>Java NIO2 (Path、Paths 与 Files)</h2><ul>
<li>随着 JDK 7 的发布，Java对NIO进行了极大的扩展，增强了对文件处理和文件系统特性的支持，以至于我们称他们为 NIO.2。因为 NIO 提供的一些功能，NIO已经成为文件处理中越来越重要的部分。</li>
</ul>
<h3 id="Path-与-Paths"><a href="#Path-与-Paths" class="headerlink" title="Path 与 Paths"></a>Path 与 Paths</h3><ul>
<li>java.nio.file.Path 接口代表一个平台无关的平台路径，描述了目录结构中文件的位置。</li>
<li>Paths 提供的 get() 方法用来获取 Path 对象：<ul>
<li>Path get(String first, String … more) : 用于将多个字符串串连成路径。</li>
</ul>
</li>
<li>Path 常用方法:</li>
</ul>
<p><img src="/2019/03/01/nio基本概念和快速入门、/paths的常用用法.png" alt="paths的常用用法"></p>
<h3 id="Files类"><a href="#Files类" class="headerlink" title="Files类"></a>Files类</h3><ul>
<li>java.nio.file.Files 用于操作文件或目录的工具类。</li>
<li>Files常用方法:<ul>
<li>Path copy(Path src, Path dest, CopyOption … how) : 文件的复制</li>
<li>Path createDirectory(Path path, FileAttribute&lt;?&gt; … attr) : 创建一个目录</li>
<li>Path createFile(Path path, FileAttribute&lt;?&gt; … arr) : 创建一个文件</li>
<li>void delete(Path path) : 删除一个文件</li>
<li>Path move(Path src, Path dest, CopyOption…how) : 将 src 移动到 dest 位置</li>
<li>long size(Path path) : 返回 path 指定文件的大小</li>
</ul>
</li>
<li>Files常用方法：用于判断<ul>
<li>boolean exists(Path path, LinkOption … opts) : 判断文件是否存在</li>
<li>boolean isDirectory(Path path, LinkOption … opts) : 判断是否是目录</li>
<li>boolean isExecutable(Path path) : 判断是否是可执行文件</li>
<li>boolean isHidden(Path path) : 判断是否是隐藏文件</li>
<li>boolean isReadable(Path path) : 判断文件是否可读</li>
<li>boolean isWritable(Path path) : 判断文件是否可写</li>
<li>boolean notExists(Path path, LinkOption … opts) : 判断文件是否不存在</li>
<li>public static <a extends="" basicfileattributes=""> A readAttributes(Path path,Class<a> type,LinkOption… options) : 获取与 path 指定的文件相关联的属性。</a></a></li>
</ul>
</li>
<li>Files常用方法：用于操作内容<ul>
<li>SeekableByteChannel newByteChannel(Path path, OpenOption…how) : 获取与指定文件的连接，how 指定打开方式。</li>
<li>DirectoryStream newDirectoryStream(Path path) : 打开 path 指定的目录</li>
<li>InputStream newInputStream(Path path, OpenOption…how):获取 InputStream 对象</li>
<li>OutputStream newOutputStream(Path path, OpenOption…how) : 获取 OutputStream 对象</li>
</ul>
</li>
</ul>
<h2 id="自动资源"><a href="#自动资源" class="headerlink" title="自动资源"></a>自动资源</h2><ul>
<li>Java 7 增加了一个新特性，该特性提供了另外一种管理资源的方式，这种方式能自动关闭文件。这个特性有时被称为自动资源管理(Automatic Resource Management, ARM)， 该特性以 try 语句的扩展版为基础。自动资源管理主要用于，当不再需要文件（或其他资源）时，可以防止无意中忘记释放它们。</li>
<li>自动资源管理基于 try 语句的扩展形式。</li>
</ul>
<p><img src="/2019/03/01/nio基本概念和快速入门、/自动资源管理.png" alt="自动资源管理"></p>
<p><code>注意：</code></p>
<p>①try 语句中声明的资源被隐式声明为 final ，资源的作用局限于带资源的 try 语句</p>
<p>②可以在一条 try 语句中管理多个资源，每个资源以“;” 隔开即可。</p>
<p>③需要关闭的资源，必须实现了 AutoCloseable 接口或其自接口 Closeab</p>

      
    </div>
    
    
    

    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>Adhere to the original technology sharing, your support will encourage me to continue to create!</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="/wx.jpg" alt="huangsm 微信支付">
        <p>微信支付</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="/zfb.jpg" alt="huangsm 支付宝">
        <p>支付宝</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/NIO/" rel="tag"><i class="fa fa-tag"></i> NIO</a>
          
            <a href="/tags/JAVA7/" rel="tag"><i class="fa fa-tag"></i> JAVA7</a>
          
            <a href="/tags/非阻塞和阻塞/" rel="tag"><i class="fa fa-tag"></i> 非阻塞和阻塞</a>
          
            <a href="/tags/通道和选择器/" rel="tag"><i class="fa fa-tag"></i> 通道和选择器</a>
          
        </div>
      

      
      
        <div class="post-widgets">
        

        

        
          
          <div id="needsharebutton-postbottom">
            <span class="btn">
              <i class="fa fa-share-alt" aria-hidden="true"></i>
            </span>
          </div>
        
        </div>
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2019/02/25/JUC包使用/" rel="next" title="Java JUC的快速入门使用">
                <i class="fa fa-chevron-left"></i> Java JUC的快速入门使用
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope="" itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image" src="/blogHead.jpg" alt="huangsm">
            
              <p class="site-author-name" itemprop="name">huangsm</p>
              <p class="site-description motion-element" itemprop="description">Make a silk purse out of a self</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">36</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">29</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">104</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://gitee.com/wangyuanbaby" target="_blank" title="Gitee">
                      
                        <i class="fa fa-fw fa-globe"></i>Gitee</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://github.com/babybabywang" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-globe"></i>GitHub</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://blog.csdn.net/weixin_36964056" target="_blank" title="CSDN">
                      
                        <i class="fa fa-fw fa-globe"></i>CSDN</a>
                  </span>
                
            </div>
          

          
          

          
          
            <div class="links-of-blogroll motion-element links-of-blogroll-block">
              <div class="links-of-blogroll-title">
                <i class="fa  fa-fw fa-link"></i>
                Links
              </div>
              <ul class="links-of-blogroll-list">
                
                  <li class="links-of-blogroll-item">
                    <a href="https://gitee.com/wangyuanbaby" title="码云🐴" target="_blank">码云🐴</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="http://www.huangsm.xyz:7900/" title="Eureka服务器" target="_blank">Eureka服务器</a>
                  </li>
                
              </ul>
            </div>
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#NIO快速入门"><span class="nav-number">1.</span> <span class="nav-text">NIO快速入门</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#Java-NIO-简介"><span class="nav-number">1.1.</span> <span class="nav-text">Java NIO 简介</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Java-NIO-与-IO-的主要区别"><span class="nav-number">1.2.</span> <span class="nav-text">Java NIO 与 IO 的主要区别</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#缓冲区-Buffer-和通道-Channel"><span class="nav-number">1.3.</span> <span class="nav-text">缓冲区(Buffer)和通道(Channel)</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#缓冲区"><span class="nav-number">1.3.1.</span> <span class="nav-text">缓冲区</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#缓冲区的基本属性"><span class="nav-number">1.3.2.</span> <span class="nav-text">缓冲区的基本属性</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Buffer-的常用方法"><span class="nav-number">1.3.3.</span> <span class="nav-text">Buffer 的常用方法</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#缓冲区的数据操作"><span class="nav-number">1.3.4.</span> <span class="nav-text">缓冲区的数据操作</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#直接缓冲区与非直接缓冲区"><span class="nav-number">1.3.5.</span> <span class="nav-text">直接缓冲区与非直接缓冲区</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#本节代码案例"><span class="nav-number">1.3.6.</span> <span class="nav-text">本节代码案例</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#文件通道-FileChannel"><span class="nav-number">1.4.</span> <span class="nav-text">文件通道(FileChannel)</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#原始情况有CPU控制IO"><span class="nav-number">1.4.0.1.</span> <span class="nav-text">原始情况有CPU控制IO</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#DMA直接存储器"><span class="nav-number">1.4.0.2.</span> <span class="nav-text">DMA直接存储器</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#通道-Channel方式"><span class="nav-number">1.4.0.3.</span> <span class="nav-text">通道(Channel方式)</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#通道的数据传输"><span class="nav-number">1.4.0.4.</span> <span class="nav-text">通道的数据传输</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#分散-Scatter-和聚集-Gathe"><span class="nav-number">1.4.0.5.</span> <span class="nav-text">分散(Scatter)和聚集(Gathe</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#通道之间的数据传输"><span class="nav-number">1.4.0.6.</span> <span class="nav-text">通道之间的数据传输</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#字符集-Charset"><span class="nav-number">1.4.0.7.</span> <span class="nav-text">字符集(Charset)</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#FileChannel-的常用方法"><span class="nav-number">1.4.0.8.</span> <span class="nav-text">FileChannel 的常用方法</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#本节代码案例-1"><span class="nav-number">1.4.0.9.</span> <span class="nav-text">本节代码案例</span></a></li></ol></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#NIO-的非阻塞式网络通信"><span class="nav-number">1.5.</span> <span class="nav-text">NIO 的非阻塞式网络通信</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#阻塞与非阻塞"><span class="nav-number">1.5.1.</span> <span class="nav-text">阻塞与非阻塞</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#选择器-Selector"><span class="nav-number">1.5.2.</span> <span class="nav-text">选择器(Selector)</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#选择器（Selector）的应用"><span class="nav-number">1.5.2.1.</span> <span class="nav-text">选择器（Selector）的应用</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#SelectionKey"><span class="nav-number">1.5.2.2.</span> <span class="nav-text">SelectionKey</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#Selector-的常用方法"><span class="nav-number">1.5.2.3.</span> <span class="nav-text">Selector 的常用方法</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#SocketChannel"><span class="nav-number">1.5.3.</span> <span class="nav-text">SocketChannel</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#ServerSocketChannel"><span class="nav-number">1.5.4.</span> <span class="nav-text">ServerSocketChannel</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#DatagramChannel"><span class="nav-number">1.5.5.</span> <span class="nav-text">DatagramChannel</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#最终代码"><span class="nav-number">1.5.6.</span> <span class="nav-text">最终代码</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#管道-Pipe"><span class="nav-number">1.6.</span> <span class="nav-text">管道(Pipe)</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#代码"><span class="nav-number">1.6.1.</span> <span class="nav-text">代码</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Java-NIO2-Path、Paths-与-Files"><span class="nav-number">1.7.</span> <span class="nav-text">Java NIO2 (Path、Paths 与 Files)</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#Path-与-Paths"><span class="nav-number">1.7.1.</span> <span class="nav-text">Path 与 Paths</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Files类"><span class="nav-number">1.7.2.</span> <span class="nav-text">Files类</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#自动资源"><span class="nav-number">1.8.</span> <span class="nav-text">自动资源</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
<div class="copyright">&copy; 2018 &mdash; <span itemprop="copyrightYear">2019</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">HUANGSM</span>

  
</div>









        
<div class="busuanzi-count">
  <script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv">
      <i class="fa fa-user"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
      
    </span>
  

  
    <span class="site-pv">
      <i class="fa fa-eye"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
      
    </span>
  
</div>








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    
      <div id="needsharebutton-float">
        <span class="btn">
          <i class="fa fa-share-alt" aria-hidden="true"></i>
        </span>
      </div>
    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  
  
  
  <link rel="stylesheet" href="/lib/needsharebutton/needsharebutton.css">

  
  
  <script src="/lib/needsharebutton/needsharebutton.js"></script>

  <script>
    
      pbOptions = {};
      
          pbOptions.iconStyle = "box";
      
          pbOptions.boxForm = "horizontal";
      
          pbOptions.position = "bottomCenter";
      
          pbOptions.networks = "Weibo,Wechat,Douban,QQZone,Twitter,Facebook";
      
      new needShareButton('#needsharebutton-postbottom', pbOptions);
    
    
      flOptions = {};
      
          flOptions.iconStyle = "box";
      
          flOptions.boxForm = "horizontal";
      
          flOptions.position = "middleRight";
      
          flOptions.networks = "Weibo,Wechat,Douban,QQZone,Twitter,Facebook";
      
      new needShareButton('#needsharebutton-float', flOptions);
    
  </script>

  

  

  

  

</body>
</html>
